package com.dianpingmedia.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(List.class)
@MappedJdbcTypes({ JdbcType.VARCHAR })
public class ListStringTypeHandler extends BaseTypeHandler<List<String>> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ListStringTypeHandler.class);

	private static ObjectMapper mapper = new ObjectMapper();
	static {
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setSerializationInclusion(Include.NON_NULL);
	}
	private static JavaType jt=mapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);


	public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> list, JdbcType jdbcType)
			throws SQLException {
		try {
			String json = mapper.writeValueAsString(list);
			preparedStatement.setString(i, json);
		} catch (JsonProcessingException e) {
			LOGGER.warn(e.getMessage(), e);
		}

	}

	public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
		try {
			return mapper.readValue(resultSet.getString(s),jt);
		} catch (Exception e) {
			LOGGER.warn(e.getMessage());
			return null;
		}  
	}

	public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
		try {
			return mapper.readValue(resultSet.getString(i),jt);
		} catch (Exception e) {
			LOGGER.warn(e.getMessage());
			return null;
		}  
	}

	public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
		try {
			return mapper.readValue(callableStatement.getString(i),jt);
		} catch (Exception e) {
			LOGGER.warn(e.getMessage());
			return null;
		}  
	}
}
